package dk.mirasola.systemtraining.bridgewidgets.shared.factory;

import dk.mirasola.systemtraining.bridgewidgets.shared.model.distributionfiltertree.shape.ExactShapeElement;
import dk.mirasola.systemtraining.bridgewidgets.shared.model.distributionfiltertree.shape.IntervalShapeElement;
import dk.mirasola.systemtraining.bridgewidgets.shared.model.distributionfiltertree.shape.ShapeElement;
import dk.mirasola.systemtraining.bridgewidgets.shared.model.distributionfiltertree.shape.WildcardShapeElement;

public class ShapeElementFactory {
    public static String shapeElementToString(ShapeElement shapeElement) {
        if (shapeElement == null) {
            throw new NullPointerException();
        } else if (shapeElement instanceof WildcardShapeElement) {
            return "*";
        } else if (shapeElement instanceof ExactShapeElement) {
            return String.valueOf(((ExactShapeElement) shapeElement).getCardsCount());
        } else if (shapeElement instanceof IntervalShapeElement) {
            IntervalShapeElement element = (IntervalShapeElement) shapeElement;
            return element.getMinCardsCount() + ":" + element.getMaxCardsCount();
        } else {
            throw new RuntimeException("Unknown type of shape element: " + shapeElement);
        }
    }

    public static ShapeElement stringToShapeElement(String str, boolean validate) {
        if (str == null) {
            throw new NullPointerException();
        } else if (str.length() == 0) {
            throw new RuntimeException("cannot parse '" + str + "' to a shape element");
        } else if ("*".equals(str)) {
            return new WildcardShapeElement();
        } else {
            try {
                if (str.contains(":")) {
                    String[] cardCounts = str.split(":");

                    return IntervalShapeElement.create(Integer.parseInt(cardCounts[0]), Integer.parseInt(cardCounts[1]), validate);
                } else {
                    return ExactShapeElement.create(Integer.parseInt(str), validate);
                }
            } catch (NumberFormatException e) {
                throw new RuntimeException("cannot parse '" + str + "' to a shape element");
            }
        }
    }


    private ShapeElementFactory() {
    }
}
